#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量下载图片脚本
支持从 Unsplash API 下载图片
需要安装: pip install requests pillow
"""

import os
import requests
from urllib.parse import quote

# 创建图片目录
images_dir = 'images/words'
os.makedirs(images_dir, exist_ok=True)

# 单词列表（英文单词 -> 文件名）
words_map = {
    # 动物
    'cat': 'cat.png',
    'dog': 'dog.png',
    'bird': 'bird.png',
    'fish': 'fish.png',
    'rabbit': 'rabbit.png',
    'tiger': 'tiger.png',
    'lion': 'lion.png',
    'elephant': 'elephant.png',
    # 水果
    'apple': 'apple.png',
    'banana': 'banana.png',
    'orange': 'orange.png',
    'grape': 'grape.png',
    'strawberry': 'strawberry.png',
    'watermelon': 'watermelon.png',
    'pear': 'pear.png',
    'peach': 'peach.png',
    # 颜色
    'red': 'red.png',
    'blue': 'blue.png',
    'green': 'green.png',
    'yellow': 'yellow.png',
    'orange color': 'orange-color.png',
    'purple': 'purple.png',
    'pink': 'pink.png',
    'black': 'black.png',
    # 数字
    'one': 'one.png',
    'two': 'two.png',
    'three': 'three.png',
    'four': 'four.png',
    'five': 'five.png',
    'six': 'six.png',
    'seven': 'seven.png',
    'eight': 'eight.png',
    'nine': 'nine.png',
    'ten': 'ten.png',
}

def download_from_unsplash(word, filename):
    """从 Unsplash 下载图片"""
    try:
        # Unsplash Source API (无需 API Key)
        url = f"https://source.unsplash.com/400x400/?{quote(word)}"
        response = requests.get(url, timeout=10, allow_redirects=True)
        
        if response.status_code == 200:
            filepath = os.path.join(images_dir, filename)
            with open(filepath, 'wb') as f:
                f.write(response.content)
            
            # 转换为 PNG 格式（如果需要）
            from PIL import Image
            img = Image.open(filepath)
            if img.format != 'PNG':
                img = img.convert('RGBA')
                filepath_png = filepath.replace('.png', '.png')
                img.save(filepath_png, 'PNG')
                if filepath != filepath_png:
                    os.remove(filepath)
            
            print(f"✓ 下载成功: {filename}")
            return True
        else:
            print(f"✗ 下载失败: {filename} (状态码: {response.status_code})")
            return False
    except Exception as e:
        print(f"✗ 下载失败: {filename} - {e}")
        return False

def download_from_placeholder(word, filename):
    """使用占位图片服务（备用方案）"""
    try:
        # 使用 placeholder.com 生成占位图片
        url = f"https://via.placeholder.com/400x400/4A90E2/FFFFFF?text={quote(word.upper())}"
        response = requests.get(url, timeout=10)
        
        if response.status_code == 200:
            filepath = os.path.join(images_dir, filename)
            with open(filepath, 'wb') as f:
                f.write(response.content)
            print(f"✓ 生成占位图: {filename}")
            return True
    except Exception as e:
        print(f"✗ 生成失败: {filename} - {e}")
    return False

print("开始下载图片...\n")
print("提示：如果 Unsplash 下载失败，将使用占位图片\n")

success_count = 0
fail_count = 0

for word, filename in words_map.items():
    if os.path.exists(os.path.join(images_dir, filename)):
        print(f"○ 已存在: {filename}")
        success_count += 1
        continue
    
    # 尝试从 Unsplash 下载
    if download_from_unsplash(word, filename):
        success_count += 1
    else:
        # 如果失败，使用占位图片
        if download_from_placeholder(word, filename):
            success_count += 1
        else:
            fail_count += 1

print(f"\n下载完成！")
print(f"成功: {success_count} 个")
print(f"失败: {fail_count} 个")
print(f"文件保存在 {images_dir}/ 目录")

